import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  // 加载环境变量
  const env = loadEnv(mode, process.cwd(), '')

  return {
    plugins: [vue()],
    server: {
      port: parseInt(env.VITE_FRONTEND_PORT) || 8002,
      host: true,
      cors: true,
      allowedHosts: [
        'office20.inoteexpress.com',
        'localhost',
        '127.0.0.1'
      ],
      // 开发环境代理配置
      proxy: {
        '/api': {
          target: 'http://127.0.0.1:8001', // 使用IPv4地址避免IPv6问题，更新为8001端口
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ''),
          secure: false,
          configure: (proxy, options) => {
            proxy.on('error', (err, req, res) => {
              console.log('Proxy error:', err)
            })
            proxy.on('proxyReq', (proxyReq, req, res) => {
              console.log('Proxying request to:', req.url)
            })
          }
        }
      }
    },
    preview: {
      port: parseInt(env.VITE_FRONTEND_PORT) || 8002,
      host: true,
      cors: true,
      allowedHosts: [
        'office20.inoteexpress.com',
        'localhost',
        '127.0.0.1'
      ]
    },
    build: {
      outDir: 'dist',
      sourcemap: mode === 'development',
      // 生产环境构建配置
      rollupOptions: {
        output: {
          manualChunks: undefined
        }
      }
    }
  }
})
